package com.cfushn.ddd.tools.other;

import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 * RegUtil
 *
 * @author CFuShn 2022/3/7 16:03
 */
@SuppressWarnings("unused")
public class RegUtil {

    /**
     * 正则匹配
     *
     * @param regex 正则
     * @param input 字符串
     * @return 验证成功返回 true，验证失败返回 false
     */
    public static boolean regexFind(String regex, CharSequence input) {
        if (null == input) {
            return false;
        }
        return Pattern.compile(regex).matcher(input).find();
    }

    /**
     * split string by char,out of bracket (regular-like)
     *
     * @author CFuShn at 2022/3/7 16:04
     */
    public static String[] splitOutOfBracket(String text, char c) {

        if (StringUtils.isBlank(text)) {
            text = "";
        }

        char[] characters = text.toCharArray();
        int stack1 = 0;
        int stack2 = 0;
        int stack3 = 0;
        for (int i = 0; i < characters.length; i++) {
            if (characters[i] != c) {
                if (characters[i] == '(') {
                    stack1++;
                } else if (characters[i] == ')') {
                    stack1--;
                } else if (characters[i] == '[') {
                    stack2++;
                } else if (characters[i] == ']') {
                    stack2--;
                } else if (characters[i] == '{') {
                    stack3++;
                } else if (characters[i] == '}') {
                    stack3--;
                }
            } else if (stack1 == 0 && stack2 == 0 && stack3 == 0) {
                characters[i] = 'β';
            }
        }
        return String.valueOf(characters).split("β");
    }
}

